<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Article extends CF_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->model('article_mdl');
		$this->load->library('category');
		$this->uid = $this->user_login->is_logged_in() ? $this->user_login->get_user_id() : 0;
	}

	public function index()
	{
		$this->lists();
	}
	/**
	 * 菜谱内容页
	 * @param  string $id [description]
	 * @return [type]     [description]
	 */
	public function views($id='')
	{
		
		$this->load->model('user/user_guanzhu','uguanzhu');
		$this->load->helper('text');
		
		/** 如为空，则跳转 */
		if (empty($id) || !is_numeric($id)) redirect(site_url());
		//获取菜谱信息
		$article_info = $this->article_mdl->get_by(array('id'=>intval($id)));

		/** 不存在? */
		if (!$article_info) show_404();

		/** 内容显示格式化 */
		$data['article_info'] = $this->_prepare_article_info($article_info);

		//更新菜谱浏览次数
		$this->article_mdl->update_views(intval($id));



		$data['if_guanzhu'] = $this->uguanzhu->get_user_guanzhu($data['article_info']['uid'], $this->uid); //guanzhu

		$data['user_avartar'] = $this->user_login->get_avatar_dir($data['article_info']['uid']);
		$data['article_hot'] = $this->article_mdl->get(NULL, 0, 10, 'views DESC')->result_array();
		$data['cate'] = $this->category->getAllCategory(0, false, 1, false, 1);
		$data['cid'] = $article_info['cid'];

		$this->load->view('article_views',$data);
	}

	public function lists($cid = '', $page = '')
	{
		$cid = $cid ? $cid : '119';
		$page = max(1, intval($page));
		$limit = 20; //每页显示数
		$offset = ($page - 1) * $limit;
		$article_list = $this->article_mdl->get(array('cid'=>intval($cid)), $offset, $limit)->result_array();
		$data_count = 50000; 
		/** 不存在? */
		if (!$article_list) show_404();
		
		/* 分页配置 */
		$this->load->library('pagination');
		$config['base_url'] = site_url('article/lists/'.$cid.'/');
		$config['total_rows'] = $data_count;
		$config['per_page'] = $limit; 
		$config['uri_segment'] = 4;
		$this->pagination->initialize($config); 

		$data['article_list'] = $article_list;
		$data['article_hot'] = $this->article_mdl->get(NULL, 0, 10, 'views DESC')->result_array();
		$data['cate'] = $this->category->getAllCategory(0, false, 1, false, 1);
		$data['cid'] = $cid;
		$data['cate_info'] = $this->category->fetchOne($cid);
		$this->load->view('article',$data);
	}

	private function _prepare_article_info($article_info)
	{
		$this->load->model('user/users','users');

		//获取发布此菜的用户
		$user_info = $this->users->get_user_by_id($article_info['uid'])->row();
		/** 获取发布菜谱的用户信息 */
		$article_info['user_avartar'] = $this->user_login->get_avatar_dir($article_info['uid']); 
		$article_info['username'] = $user_info->username;
		$article_info['userid'] = $user_info->id; 


		
		return $article_info;
	}
}

/* End of file article.php */
/* Location: ./application/controllers/article.php */